<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Factories\HasFactory;


/**
 * 在线抽奖活动分享次数表
 */
class TurnActivityShare extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'turn_activity_share';


     /**
     * 修改
     * @param $data 修改的数据
     * @param $field 要修改的字段名  空数据表示全部都修改
     * @param $findWhere 查询条件  如果为空，则用数据里面的id 和 id值作为检索条件
     */
    public function change($data, $field = [], $findWhere = [])
    {
        $res = $this->where('user_guid' , $data['user_guid'])->where('act_id' , $data['act_id'])->where('date' , date('Y-m-d'))->first();
        if($res){
            $res->number = ++ $res->number;
            $res->save();
            return $res->number;
        }
        $this->act_id = $data['act_id'];
        $this->user_guid = $data['user_guid'];
        $this->number = 1;
        $this->date = date('Y-m-d');
        $this->save();
        return $this->number;
    }


    /**
     * 获取分享次数
     * @param $act_id 活动id
     * @param $user_guid 用户guid
     * @param $date 日期  2022-03-29
     */
    public function getUserShareNumber($act_id, $user_guid = null, $date=null, $start_time = null, $end_time = null)
    {
        return $this->where('act_id', $act_id)->where(function ($query) use ($user_guid, $date, $start_time, $end_time) {
            if ($user_guid) {
                $query->where('user_guid', $user_guid);
            }
            if ($date) {
                $query->where('date', $date);
            }
            if ( $start_time && $end_time) {
                $query->whereBetween('create_time', [$start_time , $end_time]);
            }
        })->sum('number');
    }
}
